<template>
  <div class="history-record">
    <el-scrollbar>
      <div class="top-card-container">
        <dataCard :dataArr="cardList" :code="statusCode"></dataCard>
      </div>
    </el-scrollbar>
    <div class="chart-content">
      <div class="filter-content"> </div>

      <div id="historyChart"></div>
    </div>
  </div>
</template>
<script setup lang="ts">
  import * as echarts from 'echarts'
  import dayjs from 'dayjs'
  import { formatDuration } from '@/utils/common/date'
  import { dataRegroup } from '../components/utils'
  import dataCard from './dataCard.vue'
  import {
    getZhuangTaiZongLan_xs,
    getHuanDuanJiLu_5,
    getHuoQuHuanDuanJiLu
  } from '@/api/shengChanJianShi'

  defineProps({
    statusCode: String
  })

  const recordValue = ref('')
  const machineText = ref('')
  const machineId = ref('')
  const machineList = ref<any>([])
  const recordList = ref<any>([])
  const cardList = ref<any>([])

  const getMachineInfo = () => {
    getZhuangTaiZongLan_xs().then((res: any) => {
      machineList.value = res.map((value) => {
        return {
          name: value.machineName,
          id: value.id,
          craftNodeName: value.craftNodeName
        }
      })
      machineText.value = machineList.value[0].name
      machineId.value = machineList.value[0].id
      getRecordInfo()
    })
  }

  const getRecordInfo = () => {
    getHuanDuanJiLu_5(machineId.value).then((res: any) => {
      recordList.value = res.map((value) => {
        let str =
          value.actualChangeTime == null
            ? '至今'
            : dayjs(value.actualChangeTime).format('MM-DD HH:mm')
        return {
          fK_RovingRenewXS: value.fK_RovingRenewXS,
          machineDocumentId: value.machineDocumentId,
          time: dayjs(value.changeTime).format('MM-DD HH:mm') + '~' + str
        }
      })
      recordValue.value = recordList.value[0].fK_RovingRenewXS
      getInfoData()
    })
  }

  const actualChangeTime = ref()
  const remark = ref('')
  const predictionList = ref<any>([])
  const xAxisData = ref<any>([])
  const yAxisData1 = ref<any>([])
  const getInfoData = () => {
    getHuoQuHuanDuanJiLu(recordValue.value).then((res: any) => {
      cardList.value = dataRegroup({
        passRateBy2Hour: res.passRateBy2Hour,
        passRateBy1Hour: res.passRateBy1Hour,
        passRateByHalfHour: res.passRateByHalfHour
      })
      //   actualChangeTime.value = res.actualChangeTime
      //     ? dayjs(res.actualChangeTime).format('YYYY-MM-DD HH:mm')
      //     : null
      actualChangeTime.value = dayjs(res.actualChangeTime).format('YYYY-MM-DD HH:mm')
      remark.value = res.remark

      for (let index = 0; index < res.details.length; index++) {
        const val = res.details[index]
        predictionList.value.push({
          predictionChangeTimeNext: val.predictionChangeTimeNext,
          timeStamp: val.timeStamp,
          evaluateInfo: val.evaluateInfo == null ? null : JSON.parse(val.evaluateInfo)
        })
        yAxisData1.value.push([
          dayjs(val.timeStamp).format('YYYY-MM-DD HH:mm'),
          dayjs(val.predictionChangeTimeNext).format('YYYY-MM-DD HH:mm')
        ])
      }
      //   res.details.map((val) => {

      //     // xAxisData.value.push(dayjs(val.timeStamp).format('MM-DD HH:mm'))
      //   })
      nextTick(() => {
        handleSetVisitChart()
      })
    })
  }

  const myChart = ref()
  const color = ref(['#00CA69'])
  const handleSetVisitChart = () => {
    myChart.value = echarts.init(document.getElementById('historyChart'))
    let option = {
      backgroundColor: '#fff',
      color: color.value,
      legend: {
        top: 10
      },
      tooltip: {
        trigger: 'axis',
        formatter: function (params) {
          // 数组：取鼠标悬浮当前项索引params[0].dataIndex
          let index = params[0].dataIndex

          let dict = predictionList.value[index].evaluateInfo // 通过索引取当前项完整的接口返回值
          let obj: any = {}
          let html = ''
          if (dict != null && dict != undefined) {
            obj = dict.RovingInfo
            if (obj != null) {
              params.forEach((v) => {
                if (dict != null && dict != undefined) {
                  if (dict.RovingInfo != null) {
                    html += `<div style="color: #666;font-size: 14px;line-height: 24px">
                   <div style="color: #00CA69">${v.seriesName}</div>
                   <div ><span style="display: inline-block; width: 110px; text-align: right">换段预测时间：</span>${
                     v.value[1]
                   }</div>
                   <div ><span style="display: inline-block; width: 110px; text-align: right">记录时间：</span>${
                     v.value[0]
                   }</div>
                   <div class="flex flex-align-center">
                    <div  style="width: 30px; height: 1px; border-bottom: 1px dashed #5a5a5a"> </div>
                   <div  style="flex-shrink: 0; margin-left: 5px; margin-right: 5px;">依 据</div>
                    <div style="flex-grow: 1; height: 1px; border-bottom: 1px dashed #5a5a5a"></div>
                  </div>

                   <div ><span style="display: inline-block; width: 110px; text-align: right">平均后罗拉速度：</span>${
                     obj.BackRollerSpeed == null
                       ? null
                       : Math.round(obj.BackRollerSpeed * 100) / 100
                   } rpm</div>
                   <div ><span style="display: inline-block; width: 110px; text-align: right">平均锭速：</span>${
                     obj.SpindleSpeed == null ? null : Math.round(obj.SpindleSpeed * 100) / 100
                   } r/min</div>
                   <div ><span style="display: inline-block; width: 110px; text-align: right">粗纱消耗速度：</span>${
                     obj.CsSpeed == null ? null : Math.round(obj.CsSpeed * 100) / 100
                   } m/min</div>
                   <div ><span style="display: inline-block; width: 110px; text-align: right">络纱时长：</span>${
                     obj.RovingDuration == null ? null : formatDuration(obj.RovingDuration)
                   }</div>
                   <div ><span style="display: inline-block; width: 110px; text-align: right">牵伸倍数：</span>${
                     obj.DraftTimes == null ? null : Math.round(obj.DraftTimes * 100) / 100
                   }</div>
                   <div ><span style="display: inline-block; width: 110px; text-align: right">络纱开始时间：</span>${
                     obj.Start == null ? null : dayjs(obj.Start).format('YYYY-MM-DD HH:mm')
                   }</div>
                `
                  } else {
                    html += `<div style="color: #666;font-size: 14px;line-height: 24px">
                   <div style="color: #00CA69">${v.seriesName}</div>
                   <div ><span style="display: inline-block; width: 100px; text-align: right">换段预测时间：</span>${v.value[1]}</div>
                   <div ><span style="display: inline-block; width: 100px; text-align: right">记录时间：</span>${v.value[0]}</div>
                `
                  }
                }
              })
            } else {
              params.forEach((v) => {
                html += `<div style="color: #666;font-size: 14px;line-height: 24px">
                   <div style="color: #00CA69">${v.seriesName}</div>
                   <div ><span style="display: inline-block; width: 100px; text-align: right">换段预测时间：</span>${v.value[1]}</div>
                   <div ><span style="display: inline-block; width: 100px; text-align: right">记录时间：</span>${v.value[0]}</div>
                `
              })
            }
          } else {
            params.forEach((v) => {
              html += `<div style="color: #666;font-size: 14px;line-height: 24px">
                   <div style="color: #00CA69">${v.seriesName}</div>
                   <div ><span style="display: inline-block; width: 100px; text-align: right">换段预测时间：</span>${v.value[1]}</div>
                   <div ><span style="display: inline-block; width: 100px; text-align: right">记录时间：</span>${v.value[0]}</div>
                `
            })
          }

          return html
        },
        extraCssText:
          'background: #fff; border-radius: 0;box-shadow: 0 0 3px rgba(0, 0, 0, 0.2);color: #333;',
        axisPointer: {
          type: 'shadow',
          shadowStyle: {
            color: '#ffffff',
            shadowColor: 'rgba(225,225,225,1)',
            shadowBlur: 5
          }
        }
      },
      grid: {
        top: 55,
        left: 40,
        right: 110,
        bottom: 10,
        containLabel: true
      },
      xAxis: [
        {
          type: 'time',
          name: '记录时间',
          boundaryGap: false,
          axisLabel: {
            formatter: '{value}',
            textStyle: {
              color: '#333'
            }
          },
          nameTextStyle: {
            color: color.value[0],
            fontSize: 12,
            padding: [30, 0, 0, 10] // 控制y轴标题位置
          },
          axisLine: {
            symbol: ['none', 'arrow'],
            symbolOffset: 30,
            lineStyle: {
              shadowOffsetX: 30,
              color: '#454545'
            }
          },
          data: xAxisData.value
        }
      ],
      yAxis: [
        {
          type: 'time',
          name: '换段预测时间',
          position: 'left',
          min: function (value) {
            // 取最小值向下取整为最小刻度
            if (actualChangeTime.value != null) {
              let jianGeTime = value.min - dayjs(actualChangeTime.value).valueOf()
              return (dayjs(actualChangeTime.value).valueOf() < value.min ||
                dayjs(actualChangeTime.value).valueOf() == value.min) &&
                jianGeTime < 5 * 60 * 60 * 1000
                ? dayjs(actualChangeTime.value).valueOf() + 60 * 60 * 1000
                : value.min + 60 * 60 * 1000
            } else {
              return value.min + 60 * 60 * 1000
            }
          },
          max: function (value) {
            // 取最大值向上取整为最大刻度
            if (actualChangeTime.value != null) {
              let jianGeTime = value.max - dayjs(actualChangeTime.value).valueOf()
              return (dayjs(actualChangeTime.value).valueOf() > value.max ||
                dayjs(actualChangeTime.value).valueOf() == value.max) &&
                jianGeTime > 5 * 60 * 60 * 1000
                ? dayjs(actualChangeTime.value).valueOf() + 60 * 60 * 1000
                : value.max + 60 * 60 * 1000
            } else {
              return value.max + 60 * 60 * 1000
            }
          },
          offset: 0,
          axisLabel: {
            textStyle: {
              color: '#333'
            }
          },
          nameTextStyle: {
            color: color.value[0],
            fontSize: 12,
            padding: [-30, 0, 0, -90] // 控制y轴标题位置
          },
          // 分割线
          splitLine: {
            show: false,
            lineStyle: {
              type: 'dashed',
              color: '#E9E9E9'
            }
          },
          axisLine: {
            show: true,
            symbol: ['none', 'arrow'],
            symbolOffset: 30,
            lineStyle: {
              shadowOffsetY: -30,
              color: '#454545'
            }
          },
          axisTick: {
            show: true
          }
        }
      ],
      series: [
        {
          name: '机台' + machineText.value,
          type: 'line',
          smooth: true,
          yAxisIndex: 0,
          symbolSize: 0,
          markLine: {
            lineStyle: {
              color: '#f32626',
              type: 'dashed'
            },
            data: [{ name: '实际换段时间', yAxis: actualChangeTime.value }]
          },
          zlevel: 3,
          lineStyle: {
            normal: {
              color: color.value[0],
              shadowBlur: 3,
              shadowColor: hexToRgba(color.value[0], 0.5),
              shadowOffsetY: 8
            }
          },
          symbol: 'circle', // 数据交叉点样式
          areaStyle: {
            normal: {
              color: new echarts.graphic.LinearGradient(
                0,
                0,
                0,
                1,
                [
                  {
                    offset: 0,
                    color: hexToRgba(color.value[0], 0.3)
                  },
                  {
                    offset: 1,
                    color: hexToRgba(color.value[0], 0.1)
                  }
                ],
                false
              ),
              shadowColor: hexToRgba(color.value[0], 0.1),
              shadowBlur: 10
            }
          },
          data: yAxisData1.value
        }
      ]
    }
    myChart.value.setOption(option, true)
    window.addEventListener('resize', function () {
      myChart.value.resize()
    })
  }

  const hexToRgba = (hex, opacity) => {
    let rgbaColor = ''
    let reg = /^#[\da-f]{6}$/i
    if (reg.test(hex)) {
      rgbaColor = `rgba(${parseInt('0x' + hex.slice(1, 3))},${parseInt(
        '0x' + hex.slice(3, 5)
      )},${parseInt('0x' + hex.slice(5, 7))},${opacity})`
    }
    return rgbaColor
  }

  onMounted(() => {
    getMachineInfo()
    // nextTick(() => {
    //   echarstHeigth.value = 'calc(100% - 190px)'
    // })
    // window.addEventListener('resize', () => {
    //   nextTick(() => {
    //     echarstHeigth.value = document.documentElement.clientHeight - 200
    //   })
    // })
  })
</script>
<style scoped lang="scss">
  .top-card-container {
    display: flex;
    margin-bottom: 20px;
  }

  #historyChart {
    height: calc(100vh - 355px);
  }
</style>
